package com.yami.shop.platform.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.event.SendPersonMessageEvent;
import com.yami.shop.bean.model.Blog;
import com.yami.shop.bean.model.Comment;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.param.NotifyTemplateParam;
import com.yami.shop.bean.vo.CommentMannageVo;
import com.yami.shop.bean.vo.CommentVO;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.ECommentType;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.StringUtils;
import com.yami.shop.service.BlogService;
import com.yami.shop.service.CommentService;
import com.yami.shop.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 功能描述: 评论点赞
 * @Author: LSR
 * @Date: 2022/12/28 10:00
 */

@RestController
@RequestMapping("/admin/blogComment")
@Tag(name="评论点赞接口")
@Slf4j
public class BlogCommentController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 获取评论列表
     * 盖楼接口
     * @param commentMannageVo
     * @param
     * @return
     */
    @Operation(summary =  "获取评论列表", description = "获取评论列表")
    @GetMapping("/getList")
    public ServerResponseEntity<IPage<CommentMannageVo>> getList(PageParam<CommentMannageVo> page ,  CommentMannageVo commentMannageVo) {
        IPage<CommentMannageVo> adminAllCommentList = commentService.getAdminAllCommentList(page,commentMannageVo);
        List<Long> toUidList = adminAllCommentList.getRecords().stream().filter(s -> ObjectUtil.isNotNull(s.getToUid())).map(CommentMannageVo::getToUid).collect(Collectors.toList());
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.in("uid",toUidList);
        //分页
        wrapper.eq("status", 1);
        wrapper.eq("type", ECommentType.COMMENT);
        // 查询出该文章下所有的子评论
        List<Comment> allCommentList = commentService.list(wrapper);
        Map<Long, Comment> collect2 =allCommentList.stream().collect(Collectors.toMap(Comment::getUid, Function.identity()));
        adminAllCommentList.getRecords().stream().filter(s -> ObjectUtil.isNotNull(s.getToUid())).forEach(s->{
            s.setContent(collect2.get(s.getUid()).getContent());
        });
        return ServerResponseEntity.success(adminAllCommentList);
    }

    @Operation(summary =  "获取详情", description = "获取评论列表")
    @GetMapping("/getDetailByUid")
    public ServerResponseEntity<CommentMannageVo> getDetailByUid(@RequestParam Long Uid) {
        CommentMannageVo commentMannageVo = new CommentMannageVo();
        commentMannageVo.setUid(Uid);
        List<CommentMannageVo> adminAllCommentList = commentService.getAdminAllCommentList(commentMannageVo);
        return ServerResponseEntity.success(adminAllCommentList.get(0));
    }

    @GetMapping("/getComment/by/{id}")
    @Operation(summary =  "评论详情", description = "评论详情")
    public ServerResponseEntity<Comment> getById(@PathVariable("id") Long id){
        Comment comment = commentService.getById(id);
        return ServerResponseEntity.success(comment);
    }

    /**
     * blogUid 博客id userUid  用户id 内容content 字数限制2048 source固定值 传1    toUid 如果为空代表博客首评 非空 传恢复的评论的id
     * @param commentVO
     * @return
     */
    @Operation(summary =  "增加评论", description = "增加评论")
    @PostMapping("/add")
    public ServerResponseEntity<Comment> add(@RequestBody CommentVO commentVO) {
        if(StrUtil.isEmpty(commentVO.getContent())){
            return ServerResponseEntity.showFailMsg("内容不能不能为空");
        }
        // 判断该博客是否开启评论功能
        if (ObjectUtil.isNull(commentVO.getBlogUid())) {
            Blog blog = blogService.getById(commentVO.getBlogUid());
            if ("0".equals(blog.getOpenComment())) {
                return ServerResponseEntity.showFailMsg("该评论禁止评论");
            }
        }
        String userUid = "admin";
        // 判断字数是否超过限制
        if (commentVO.getContent().length() > 2048) {
            return ServerResponseEntity.showFailMsg("userid不能为空");
        }
        Comment comment = new Comment();
        // 判断被评论的用户，是否开启了评论提醒
        //用户发消息
//            User toUser = userService.getById(commentVO.getToUserUid());
        Comment toComment = commentService.getById(commentVO.getToUid());
        if (toComment != null && StringUtils.isNotEmpty(toComment.getContent())) {
            //DOTO 消息
        }
        commentVO.setToUserUid(toComment.getUserUid());
        comment.setToUid(commentVO.getToUid());
        comment.setToUserUid(commentVO.getToUserUid());
        comment.setUserUid(userUid);
        comment.setSource(commentVO.getSource());
        comment.setBlogUid(commentVO.getBlogUid());
        comment.setContent(commentVO.getContent());
        comment.setCreateTime(new Date());
        // 当该评论不是一级评论时，需要设置一级评论UID字段 富二代
        // 表示 toComment是非一级评论
        if (!Objects.isNull(toComment.getFirstCommentUid())) {
            comment.setFirstCommentUid(toComment.getFirstCommentUid());
        } else {
            // 表示父评论是一级评论，直接获取UID
            comment.setFirstCommentUid(toComment.getUid());
        }
        String touserUid = toComment.getUserUid();
        User toUser = userService.getById(touserUid);
        toComment.setUserName(toUser.getNickName());
        comment.setToComment(toComment);

        comment.setStatus(1);
        commentService.save(comment);
        // 如果是回复某人的评论，那么需要向该用户Redis收件箱中中写入一条记录
        if (!"admin".equals(comment.getToUserUid())) {
            NotifyTemplateParam shopParam = new NotifyTemplateParam();
            shopParam.setShopId(Constant.PLATFORM_SHOP_ID);
            shopParam.setSendType(SendType.COMMENT_REMINDER.getValue());
            shopParam.setUserId(commentVO.getToUserUid());
            shopParam.setContent(commentVO.getContent());
            shopParam.setFromUserId("admin");
            shopParam.setBlogId(commentVO.getBlogUid().toString());
            shopParam.setProdId(commentVO.getToUid());
            shopParam.setType(1);
            applicationContext.publishEvent(new SendPersonMessageEvent(shopParam));
        }
        return ServerResponseEntity.success(comment);
    }


    /**
     * 通过UID删除评论
     *
     * @param commentVO
     * @return
     */
    @Operation(summary =  "删除评论", description = "删除评论")
    @PostMapping("/delete")
    public ServerResponseEntity deleteBatch(@RequestBody CommentVO commentVO) {
        Comment comment = commentService.getById(commentVO.getUid());
        // 获取该评论下的子评论进行删除
        // 传入需要被删除的评论 【因为这里是一条，我们需要用List包装一下，以后可以用于多评论的子评论删除】
        List<Comment> commentList = new ArrayList<>(1);
        commentList.add(comment);

        // 判断删除的是一级评论还是子评论
        Long firstCommentUid ;
        if (!ObjectUtil.isNull(comment.getFirstCommentUid())) {
            // 删除的是子评论
            firstCommentUid = comment.getFirstCommentUid();
        } else {
            // 删除的是一级评论
            firstCommentUid = comment.getUid();
        }

        // 获取该评论一级评论下所有的子评论
        LambdaQueryWrapper<Comment> blogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        blogLambdaQueryWrapper.eq(Comment::getFirstCommentUid, firstCommentUid);
        blogLambdaQueryWrapper.eq(Comment::getStatus, 1);
        List<Comment> toCommentList = commentService.list(blogLambdaQueryWrapper);
        List<Comment> resultList = new ArrayList<>();
        this.getToCommentList(comment, toCommentList, resultList);
        // 将所有的子评论也删除
        resultList.add(comment);//添加本身
        if (resultList.size() > 0) {
            //删除子级点赞
            List<Long> collect = resultList.stream().map(s -> s.getUid()).collect(Collectors.toList());
            LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(Comment::getToUid, collect);
            wrapper.eq(Comment::getType, ECommentType.PRAISE);//点赞
            wrapper.eq(Comment::getStatus,1);//正常
            List<Comment> list = commentService.list(wrapper);
            //评论和点赞集合合并
            resultList.addAll(list);
            resultList.forEach(item -> {
                item.setStatus(0);
                item.setUpdateTime(new Date());
            });
            commentService.updateBatchById(resultList);
        }
        //删除博客品论 更新博客点赞数量
        if(ObjectUtil.isNull(comment.getFirstCommentUid())){
            blogService.addAndCancelCommentCount(comment.getBlogUid() ,false);
        }
        return ServerResponseEntity.success();
    }

    /**
     * 获取某条评论下的所有子评论
     *
     * @return
     */
    private void getToCommentList(Comment comment, List<Comment> commentList, List<Comment> resultList) {
        if (comment == null) {
            return;
        }
        Long commentUid = comment.getUid();
        for (Comment item : commentList) {
            if (commentUid.equals(item.getToUid())) {
                resultList.add(item);
                // 寻找子评论的子评论
                getToCommentList(item, commentList, resultList);
            }
        }
    }
}
